<?php

namespace App\Http\Controllers\Web;

use App\Http\Requests\MenuRequest;
use App\Services\Menu;

/**
 * Class MenuController 菜单控制器
 * @package App\Http\Controllers\Web
 */
class MenuController extends BaseController
{
    /**
     * MenuController constructor.
     */
    public function __construct()
    {
        $this->service = Menu::getInstance();
    }

    /**
     * index 菜单列表
     * @param MenuRequest $request
     * @return object
     * @throws \Exception
     */
    public function index(MenuRequest $request): object
    {
        // pid筛选
        if ($request->get('pid') != null) {
            $condition[] = ['menus.pid', '=', $request->get('pid')];
        }
        // 层级筛选
        if (!empty($request->get('level'))) {
            $condition[] = ['menus.level', '=', $request->get('level')];
        }
        // 关键词搜索
        if (!empty($request->get('keyword'))) {
            $condition[] = ['menus.title', 'like', '%' . $request->get('keyword') . '%'];
        }
        $list = $this->service->getList($condition ?? []);

        return $this->success('查询成功', $list);
    }

    /**
     * store 新增菜单
     * @param MenuRequest $request
     * @return object
     * @throws \Exception
     */
    public function store(MenuRequest $request): object
    {
        $this->service->insertData($request->all());

        return $this->success('新增成功');
    }

    /**
     * update 更新菜单
     * @param MenuRequest $request
     * @param int $id
     * @return object
     * @throws \Exception
     */
    public function update(MenuRequest $request, int $id): object
    {
        $this->service->updateData($id, $request->all());

        return $this->success('更新成功', []);
    }

    /**
     * tree 菜单树
     *
     * @param MenuRequest $request
     * @return object
     */
    public function tree(MenuRequest $request)
    {
        // 层级筛选
        if (!empty($request->get('level'))) {
            $level = explode(',', $request->get('level'));
            $condition[] = [function ($query) use ($level) {
                $query->whereIn('level', $level);
            }];
        }
        $condition['status'] = 1;
        $list = $this->service->getMenusTree($condition);

        return $this->success('查询成功', $list);
    }

}
